<template>
	<StatusBar/>
	<page-wrapper :page-path="'/pages/chart/chart'" :navLeft="'none'" :navBackgroundColor="primaryColor"
		:navTitleStyle="navTitleStyle" :showNavbar="false">
		<view class="chart-container">
			<!-- 支出/收入切换 -->
			<view class="type-selector">
				<text :class="{ active: activeType === 'expense' }" @click="switchType('expense')">支出</text>
				<text :class="{ active: activeType === 'income' }" @click="switchType('income')">收入</text>
			</view>

			<!-- 周/月/年切换器 -->
			<view class="time-selector">
				<view class="segment-control">
					<view :class="['segment-item', activeTimeRange === 'week' ? 'active' : '']"
						@click="switchTimeRange('week')">周</view>
					<view :class="['segment-item', activeTimeRange === 'month' ? 'active' : '']"
						@click="switchTimeRange('month')">月</view>
					<view :class="['segment-item', activeTimeRange === 'year' ? 'active' : '']"
						@click="switchTimeRange('year')">年</view>
				</view>
			</view>

			<!-- 统计数据展示 -->
			<view class="stats-container">
				<view class="time-label">
					<text>{{ timeRangeLabel }}</text>
				</view>

				<view class="stats-overview">
					<view class="stats-item">
						<text class="stats-value">¥{{ totalAmount.toFixed(2) }}</text>
						<text class="stats-label">总{{ activeType === 'expense' ? '支出' : '收入' }}</text>
					</view>
					<view class="stats-item">
						<text class="stats-value">¥{{ averageAmount.toFixed(2) }}</text>
						<text class="stats-label">平均值</text>
					</view>
				</view>

				<!-- 折线图 - 使用秋云 uCharts -->
				<view class="chart-area">
					<scroll-view class="chart-scroll-view" scroll-x :scroll-left="scrollLeft" @scroll="onChartScroll" 
						:show-scrollbar="false" enhanced :bounces="true">
						<view class="line-chart-container" :style="{ width: chartContainerWidth + 'px' }">
							<qiun-data-charts type="line" :opts="chartOpts" :chartData="uChartsData" :canvas2d="true"
								canvasId="lineChart" />
						</view>
					</scroll-view>
					
					<!-- 自定义滚动指示器 -->
					<view v-if="activeTimeRange === 'month' && chartLabels && chartLabels.length > 10" class="scroll-indicator">
						<text>左右滑动查看更多</text>
					</view>
				</view>
			</view>

			<!-- 排行榜 -->
			<view class="ranking-container">
				<view class="ranking-title">
					<text>{{ activeType === 'expense' ? '支出' : '收入' }}排行榜</text>
				</view>

				<scroll-view scroll-y class="ranking-list">
					<view class="ranking-item" v-for="(item, index) in rankingList" :key="index">
						<view class="ranking-left">
							<view class="category-icon" :style="{ backgroundColor: item.color + '20' }">
								<!-- <uni-icons :type="item.icon" size="24" :color="item.color"></uni-icons> -->
								<image :src="item.icon" mode="aspectFit" class="category-image"></image>
							</view>
							<view class="category-info">
								<text class="category-name">{{ item.name }}</text>
								<view class="progress-bar">
									<view class="progress-inner"
										:style="{ width: `${item.percentage}%`, backgroundColor: item.color }"></view>
								</view>
							</view>
						</view>
						<view class="ranking-right">
							<text class="ranking-amount">{{ item.amount.toFixed(2) }}</text>
							<text class="ranking-percentage">{{ item.percentage }}%</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</page-wrapper>
</template>

<script>
import { themeMixin } from '@/utils/theme.js';
import PageWrapper from '@/components/page-wrapper/page-wrapper.vue';
import { getChartData, getRankingData } from '@/api/statistics.js';

export default {
	components: {
		PageWrapper
	},
	mixins: [themeMixin],
	data() {
		return {
			navTitleStyle: {
				color: '#FFFFFF'
			},
			activeType: 'expense', // 'expense' 或 'income'
			activeTimeRange: 'week', // 'week', 'month' 或 'year'
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth() + 1,
			currentWeek: this.getWeekOfYear(new Date()),
			
			// 滚动相关
			scrollLeft: 0,
			chartContainerWidth: 300, // 默认宽度，将在updateChartData中更新

			// uCharts配置
			chartOpts: {
				color: ["#FFD84D"],
				padding: [15, 15, 10, 15],
				enableScroll: true,
				touchMoveLimit: 60, // 增加触摸移动的灵敏度
				animation: true,
				duration: 500, // 动画持续时间
				legend: {
					show: false
				},
				xAxis: {
					disableGrid: true,
					itemCount: 7,
					scrollShow: true,
					scrollAlign: 'right',
					scrollBackgroundColor: '#F6F6F6', // 滚动条背景色
					scrollColor: '#A6A6A6', // 滚动条颜色
					axisLine: true,
					axisLineColor: '#CCCCCC',
					fontSize: 10, // 设置X轴字体大小
					fontColor: '#999999' // 设置X轴字体颜色
				},
				yAxis: {
					gridType: 'dash',
					dashLength: 2,
					data: [{
						position: 'left',
						title: '金额',
						format: 'yAxisDemo',
						axisLine: true,
						axisLineColor: '#CCCCCC',
						fontSize: 10 // 设置Y轴字体大小
					}]
				},
				extra: {
					line: {
						type: 'curve',
						width: 2,
						activeType: 'hollow',
						linearType: 'custom',
						onShadow: true,
						animation: true
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						showCategory: true
					}
				}
			},
			uChartsData: {
				categories: [],
				series: []
			},

			// 数据
			totalAmount: 0,
			averageAmount: 0,
			chartData: [],
			chartLabels: [],
			timeLabel: '',
			rankingList: [],
			loading: false
		};
	},
	computed: {
		// 时间范围标签
		timeRangeLabel() {
			return this.timeLabel || (this.activeTimeRange === 'week' ? `第${this.currentWeek}周` : 
				this.activeTimeRange === 'month' ? `${this.currentMonth}月` : 
				`${this.currentYear}年`);
		}
	},
	watch: {
		activeTimeRange() {
			// 切换时间范围时获取新数据
			this.fetchData();
		},
		activeType() {
			// 切换收支类型时获取新数据
			this.fetchData();
		}
	},
	mounted() {
		// 初始加载数据
		this.fetchData();
	},
	methods: {
		// 切换收支类型
		switchType(type) {
			if (this.activeType === type) return;
			this.activeType = type;
			// 无需在此调用fetchData，watch会处理
		},

		// 切换时间范围
		switchTimeRange(range) {
			if (this.activeTimeRange === range) return;
			this.activeTimeRange = range;
			// 无需在此调用fetchData，watch会处理
		},

		// 获取数据
		async fetchData() {
			this.loading = true;
			try {
				// 显示加载提示
				uni.showLoading({
					title: '加载中...'
				});
				
				// 获取图表数据
				const chartRes = await getChartData({
					type: this.activeType,
					timeRange: this.activeTimeRange
				});
				
				// 获取排行榜数据
				const rankRes = await getRankingData({
					type: this.activeType,
					timeRange: this.activeTimeRange
				});
				console.log("排行榜数据:",rankRes);
				
				// 处理图表数据
				if (chartRes && chartRes.data) {
					const data = chartRes.data.data;
					this.totalAmount = data.totalAmount || 0;
					this.averageAmount = data.averageAmount || 0;
					this.chartData = data.chartData || [];
					
					// 解析标签（API返回的是字符串形式的数组）
					try {
						this.chartLabels = typeof data.labels === 'string' ? 
							JSON.parse(data.labels.replace(/'/g, '"')) : data.labels;
					} catch (e) {
						this.chartLabels = [];
						console.error('解析标签出错:', e);
					}
					
					this.timeLabel = data.timeLabel || '';
					
					// 更新图表数据
					this.updateChartData();
				}
				
				// 处理排行榜数据
				if (rankRes && rankRes.data) {
					this.rankingList = rankRes.data.data || [];
				}
			} catch (error) {
				console.error('获取数据失败:', error);
				uni.showToast({
					title: '获取数据失败',
					icon: 'none'
				});
			} finally {
				// 隐藏加载提示
				uni.hideLoading();
				this.loading = false;
			}
		},

		// 更新图表数据 - 适配 uCharts
		updateChartData() {
			const chartValues = Array.isArray(this.chartData) ? 
				this.chartData.map(item => typeof item === 'object' ? item.value : item) : [];
			
			// 更新 uCharts 数据格式
			this.uChartsData = {
				categories: this.chartLabels || [],
				series: [{
					name: this.activeType === 'expense' ? '支出' : '收入',
					data: chartValues,
					color: this.activeType === 'expense' ? '#FFD84D' : '#4CAF50'
				}]
			};

			// 确定每个时间范围应显示的数据点数量和图表容器宽度
			let visibleItems = 7; // 默认显示7个数据点
			
			if (this.activeTimeRange === 'week') {
				visibleItems = 7;
				this.chartContainerWidth = 300; // 默认宽度
			} else if (this.activeTimeRange === 'month') {
				// 月视图根据数据点数量动态设置宽度
				const dataLength = this.chartLabels ? this.chartLabels.length : 0;
				if (dataLength > 10) {
					// 每个数据点占用的宽度
					const itemWidth = 30;
					this.chartContainerWidth = Math.max(300, dataLength * itemWidth);
				} else {
					this.chartContainerWidth = 300;
				}
				visibleItems = this.chartLabels ? this.chartLabels.length : 10;
			} else if (this.activeTimeRange === 'year') {
				visibleItems = 12;
				this.chartContainerWidth = 300;
			}

			// 重置滚动位置
			this.scrollLeft = 0;

			// 更新 uCharts 配置
			this.chartOpts = {
				...this.chartOpts,
				enableScroll: false, // 禁用内置滚动，使用外部scroll-view
				xAxis: {
					...this.chartOpts.xAxis,
					itemCount: visibleItems,
					scrollShow: false, // 禁用内置滚动条
					fontSize: 10,
					fontColor: '#999999'
				}
			};
		},
		
		// 滚动事件处理
		onChartScroll(e) {
			this.scrollLeft = e.detail.scrollLeft;
		},

		// 获取当前是一年中的第几周
		getWeekOfYear(date) {
			const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
			const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
			return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
		}
	}
};
</script>

<style lang="scss">
.chart-container {
	position: relative;
	display: flex;
	flex-direction: column;
	padding: 30rpx;
	height: 100vh;
	box-sizing: border-box;
	overflow: hidden;
	/* 防止整体滚动 */

	// 支出/收入切换
	.type-selector {
		display: flex;
		justify-content: center;
		margin-bottom: 30rpx;
		padding-top: 20rpx;

		text {
			padding: 10rpx 40rpx;
			font-size: 36rpx;
			color: $text-color-light;
			position: relative;
			transition: all 0.3s ease;

			&.active {
				color: $text-color;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					bottom: -6rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 6rpx;
					background-color: $primary-color;
					border-radius: 3rpx;
				}
			}

			&:active {
				opacity: 0.7;
			}
		}
	}

	// 周/月/年切换器
	.time-selector {
		margin-bottom: 30rpx;

		.segment-control {
			display: flex;
			background-color: #f5f5f5;
			border-radius: 16rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

			.segment-item {
				flex: 1;
				text-align: center;
				padding: 10rpx 0;
				font-size: 28rpx;
				color: $text-color-light;
				transition: all 0.3s ease;

				&.active {
					background-color: $primary-orange;
					color: $text-color-light;
					font-weight: 400;
					box-shadow: 0 2rpx 10rpx rgba(255, 216, 77, 0.3);
				}
			}
		}
	}

	// 统计数据容器
	.stats-container {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

		.time-label {
			font-size: 28rpx;
			color: $text-color-light;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			&::before {
				content: '';
				display: inline-block;
				width: 8rpx;
				height: 28rpx;
				background-color: $primary-color;
				margin-right: 10rpx;
				border-radius: 4rpx;
			}
		}

		.stats-overview {
			display: flex;
			margin-bottom: 30rpx;

			.stats-item {
				flex: 1;
				display: flex;
				flex-direction: column;

				.stats-value {
					font-size: 44rpx;
					font-weight: bold;
					color: $text-color;
					margin-bottom: 10rpx;
				}

				.stats-label {
					font-size: 24rpx;
					color: $text-color-light;
					display: flex;
					align-items: center;

					&::before {
						content: '';
						display: inline-block;
						width: 16rpx;
						height: 4rpx;
						background-color: $primary-color;
						margin-right: 6rpx;
						border-radius: 2rpx;
					}
				}
			}
		}

		// 图表区域
		.chart-area {
			position: relative;
			
			.chart-scroll-view {
				width: 100%;
				height: 400rpx;
			}
			
			.line-chart-container {
				height: 400rpx;
				min-width: 100%;
			}
			
			.scroll-indicator {
				position: absolute;
				bottom: -20rpx;
				right: 0;
				background-color: rgba(0, 0, 0, 0.5);
				color: #fff;
				font-size: 20rpx;
				padding: 4rpx 10rpx;
				border-radius: 10rpx;
				opacity: 0.7;
			}
		}
	}

	// 排行榜
	.ranking-container {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx 30rpx 0;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.ranking-title {
			font-size: 32rpx;
			font-weight: bold;
			color: $text-color;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			&::before {
				content: '';
				display: inline-block;
				width: 8rpx;
				height: 28rpx;
				background-color: $primary-color;
				margin-right: 10rpx;
				border-radius: 4rpx;
			}
		}

		.ranking-list {
			flex: 1;
			overflow-y: auto;

			.ranking-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #f5f5f5;
				transition: all 0.3s ease;

				&:last-child {
					border-bottom: none;
				}

				&:active {
					background-color: #f9f9f9;
				}

				.ranking-left {
					display: flex;
					align-items: center;
					flex: 1;

					.category-icon {
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
						display: flex;
						justify-content: center;
						align-items: center;
						margin-right: 20rpx;
						box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
					}

					.category-info {
						flex: 1;

						.category-name {
							font-size: 28rpx;
							color: $text-color;
							margin-bottom: 10rpx;
							font-weight: 500;
						}

						.progress-bar {
							height: 10rpx;
							background-color: #f5f5f5;
							border-radius: 5rpx;
							overflow: hidden;

							.progress-inner {
								height: 100%;
								border-radius: 5rpx;
							}
						}
					}
				}

				.ranking-right {
					display: flex;
					flex-direction: column;
					align-items: flex-end;

					.ranking-amount {
						font-size: 30rpx;
						font-weight: bold;
						color: $text-color;
					}

					.ranking-percentage {
						font-size: 24rpx;
						color: $text-color-light;
						margin-top: 4rpx;
					}
				}
			}
		}
	}
}
</style>